import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:smooth_scroll_multiplatform/smooth_scroll_multiplatform.dart';
import 'package:suburban_inside_flutter/viewmodel/general_viewmodel.dart';
import 'package:suburban_inside_flutter/widget/AnimatedInsertList.dart';
import 'package:suburban_inside_flutter/widget/colorful_button.dart';
import 'package:suburban_inside_flutter/widget/listview_scrollbar.dart';
import 'package:suburban_inside_flutter/widget/search_box.dart';

import 'package:suburban_inside_flutter/viewmodel/general_viewmodel.dart';


EdgeInsetsGeometry fromLT(double left, double top) {
  return EdgeInsets.fromLTRB(left, top, left, top);
}


class ChatBox extends StatefulWidget {
  const ChatBox({
    super.key,
  });

  @override
  State<ChatBox> createState() => _ChatBoxState();
}

class _ChatBoxState extends State<ChatBox> {

  final _searchBoxFocusNode = FocusNode();
  final _searchBoxTextController = TextEditingController();
  ScrollController? _scrollViewController;

  final myBorderRadius = BorderRadius.circular(16);

  @override
  void initState() {
    GeneralViewModel().respondScrollViewmodel.addListener(() {
      // print("hit me");
      _scrollViewController?.animateTo(0, duration: const Duration(milliseconds: 100), curve: Curves.easeIn);
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        // color: const Color.fromARGB(255, 18, 18, 18)
        color: Colors.black38,
        // color: Colors.pink,
        borderRadius: myBorderRadius,
      ),
      child: ClipRRect(
        borderRadius: myBorderRadius,
        child: Stack(
          children: [
            Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                children: [
                  Row(
                    children: [
                      const SizedBox(width: 12,),
                      const Text("Console", style: TextStyle(
                        color: Colors.white,
                        fontSize: 16,
                      )),
                      Padding(
                        padding: const EdgeInsets.fromLTRB(3, 2, 0, 0),
                        child: GestureDetector(
                          onTap: () {
                            print("unimplemented: console help");
                          },
                          child: GestureDetector(
                            onTap: () {
                              print("console help tapped");
                            },
                            child: const MouseRegion(
                              cursor: SystemMouseCursors.click,
                              child: Icon(Icons.help, color: Colors.grey, size: 15,),
                            ),
                          ),
                        ),
                      ),
                      const Expanded(child: SizedBox.shrink()),
                      // MyDropDown(),
                      // IconButton(
                      //   icon: const Icon(Icons.settings),
                      //   onPressed: () {},
                      // ),
                      Tooltip(
                        message: "Clear Console",
                        waitDuration: const Duration(milliseconds: 300),
                        child: ColorfulButton(
                          fgColor: Colors.white70,
                          fgColorHover: Colors.redAccent,
                          paddingLR: 6,
                          child: const Icon(Icons.cleaning_services_sharp, size: 20),
                          onTap: () {
                            GeneralViewModel().respondScrollViewmodel.cls();
                          },
                        ),
                      ),
                      Tooltip(
                        message: "General Settings",
                        waitDuration: const Duration(milliseconds: 300),
                        child: ColorfulButton(
                          fgColor: Colors.white70,
                          fgColorHover: Colors.cyanAccent,
                          paddingLR: 6,
                          child: const Icon(Icons.settings_sharp, size: 20),
                          onTap: () {
                            print("settings tapped");
                          },
                        ),
                      )
                    ],
                  ),
        
                  // Center(child: Text("context", style: TextStyle(color: Colors.white)))
                  Expanded(
                      child: DynMouseScroll(
                        scrollSpeed: 0.86,
                        animationCurve: Curves.easeOutQuart,
                        builder: (context, controller, physics) {
                          _scrollViewController = controller;
                          return ScrollConfiguration(
                            behavior: SukietListViewScrollBehavior(),
                            child: MyAnimatedList(
                                controller: controller,
                                physics: physics,
                                listNotifier: GeneralViewModel().respondScrollViewmodel,
                                itemBuilder: (context, item, animation) {
                                  return SizeTransition(
                                    sizeFactor: animation,
                                    axis: Axis.vertical,
                                    child: Padding(
                                      padding: const EdgeInsets.fromLTRB(10, 5, 16, 5),
                                      child: ResponseView(
                                        model: item,
                                      ),
                                    ),
                                  );
                                }
                            ),
                          );
                        },
                      )
                  ),
        
                  SearchBox(
                    controller: _searchBoxTextController,
                    focusNode: _searchBoxFocusNode,
                    onTextFieldSubmitted: () {
                      print("command submitted");
                      GeneralViewModel().pushRequest(_searchBoxTextController.text);
                      _searchBoxTextController.text = "";
                    },
                  ),
                ],
              ), // ChatTestRegion(), //
            ),

            ListenableBuilder(
              listenable: GeneralViewModel().selectActionState,
              builder: (context, _) {
                return AnimatedSwitcher(
                  duration: const Duration(milliseconds: 100),
                  child: GeneralViewModel().selectActionState.selecting
                      ? BackdropFilter(
                        key: const ValueKey("context"),
                        filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
                        child: GestureDetector(
                          onTap: () {
                            print("outer space");
                            GeneralViewModel().selectActionState.cancel();
                          },
                          child: Container(
                            color: Colors.black12.withOpacity(0.2), // 可以调整透明度
                            child: Center(
                              child: Padding(
                                padding: fromLT(30, 0),
                                child: const RadiusSettingView(),
                              ),
                            ),
                          ),
                        ),
                      )
                      : const SizedBox.shrink(key: ValueKey("shrink")),
                );
              }
            )

          ],
        ),
      ),
    );
  }
}

class RadiusSettingView extends StatefulWidget {
  const RadiusSettingView({super.key});

  @override
  State<RadiusSettingView> createState() => _RadiusSettingViewState();
}

class _RadiusSettingViewState extends State<RadiusSettingView> {

  // double _radius = GeneralViewModel().selectActionState.initRadius; // 滑块的初始值

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        print("inner space");
      },
      child: Container(
        width: double.infinity,
        decoration: BoxDecoration(
            color: Colors.white70,
            borderRadius: BorderRadius.circular(10)
        ),
        child: Padding(
          padding: fromLT(18, 20),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // Align(
              //   child: Text("Step An Action",
              //     style: TextStyle(
              //         fontSize: 14,
              //         fontWeight: FontWeight.w700
              //     ),
              //   ),
              //   alignment: Alignment.centerLeft,
              // ),

              ListenableBuilder(
                listenable: GeneralViewModel().selectActionState,
                builder: (context, _) {
                  final temp = GeneralViewModel().selectActionState;
                  return Text(
                    "${temp.currentTypeName}\n(${temp.x}, ${temp.y}, ${temp.radius_raw.toStringAsFixed(2)})",
                    textAlign: TextAlign.center,
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w700
                    ),
                  );
                }
              ),

              // Slider(
              //   value: _radius, // 当前滑块的值
              //   min: 0.0, // 最小值
              //   max: 1.0, // 最大值
              //   divisions: 20, // 可选的分割数，用于创建离散的滑块
              //   label: _radius.toStringAsFixed(2), // 滑块上方显示的标签
              //   onChanged: (double newValue) {
              //     setState(() {
              //       _radius = newValue; // 更新滑块的值
              //     });
              //     GeneralViewModel().selectActionState.refreshRadius(_radius);
              //   },
              // ),

              ListenableBuilder(
                listenable: GeneralViewModel().selectActionState,
                builder: (context, _) {
                  final temp = GeneralViewModel().selectActionState;
                  print("build: ${temp.radius_raw}");
                  return Slider(
                    value: temp.radius_raw, // 当前滑块的值
                    min: 0.0, // 最小值
                    max: 1.0, // 最大值
                    divisions: 20, // 可选的分割数，用于创建离散的滑块
                    label: temp.radius_raw.toStringAsFixed(2), // 滑块上方显示的标签
                    onChanged: (double newValue) {
                      print("\n");
                      print("onChanged: $newValue");
                      temp.refreshRadius(newValue);
                    },
                  );
                }
              ),

              Row(
                children: [
                  const Expanded(child: SizedBox.shrink()),
                  ColorfulButton(
                    child: Text("cancel"),
                    style: TextStyle(height: 2),
                    fgColor: Colors.white,
                    bgColor: Colors.black54,
                    fgColorHover: Colors.white,
                    bgColorHover: Colors.redAccent,
                    onTap: () {
                      GeneralViewModel().selectActionState.cancel();
                    },
                  ),
                  const SizedBox(width: 6),
                  ColorfulButton(
                    child: Text("Step!"),
                    style: TextStyle(height: 2),
                    fgColor: Colors.white,
                    bgColor: Colors.black87,
                    fgColorHover: Colors.white,
                    bgColorHover: Colors.blue,
                    onTap: () {
                      GeneralViewModel().selectActionState.step();
                    },
                  ),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}



class ResponseView extends StatelessWidget {
  ResponseView({super.key, required this.model});

  final ResponseModel model;

  final Map<RespondStatus, Color> colors = {
    RespondStatus.ok: const Color.fromARGB(255, 41, 41, 41),
    RespondStatus.frontendErr: const Color.fromARGB(255, 214, 73, 15),
    RespondStatus.backendOff: const Color.fromARGB(255, 214, 73, 15),
    RespondStatus.backendErr: const Color.fromARGB(255, 218, 6, 6),
  };

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          width: double.infinity,
          decoration: BoxDecoration(
            color: const Color.fromARGB(255, 56, 56, 56),
            borderRadius: BorderRadius.circular(10)
          ),
          child: Padding(
            padding: const EdgeInsets.all(10),
            child: DefaultTextStyle(
              style: const TextStyle(
                color: Colors.white
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(model.request),
                  const SizedBox(height: 6),
                  Container(
                    decoration: BoxDecoration(
                      color: colors[model.status],
                      borderRadius: BorderRadius.circular(4)
                    ),
                    child: Padding(
                      padding: const EdgeInsets.all(6),
                      child: Text(model.response),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        Row(
          children: [
            const Expanded(child: SizedBox.shrink()),
            Text(formatDateTime(model.requestTime), style: const TextStyle(color: Colors.white38, fontSize: 13),),
          ],
        ),
      ],
    );
  }
}

// 手动格式化 DateTime
String formatDateTime(DateTime dateTime) {
  String year = dateTime.year.toString().padLeft(4, '0').substring(2); // 只取年份的后两位
  String month = dateTime.month.toString().padLeft(2, '0');
  String day = dateTime.day.toString().padLeft(2, '0');
  String hour = dateTime.hour.toString().padLeft(2, '0');
  String minute = dateTime.minute.toString().padLeft(2, '0');
  String second = dateTime.second.toString().padLeft(2, '0');

  return '$year-$month-$day $hour:$minute:$second';
}




class BoxTitle extends StatelessWidget {
  const BoxTitle({super.key});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text("SUBURBAN", style: styleBuilder(80)),
      ],
    );
  }
}



class MyDropDown extends StatefulWidget {
  const MyDropDown({super.key});

  @override
  State<MyDropDown> createState() => _MyDropDownState();
}

class _MyDropDownState extends State<MyDropDown> {

  // 定义下拉框的初始值
  String? _selectedValue;

  // 下拉选项
  List<String> _dropdownItems = ['CKPT 24 0820', 'CKPT 24 0823', 'CKPT 24 0907', 'CKPT 24 0915'];


  @override
  Widget build(BuildContext context) {
    return DropdownButton<String>(
      hint: Text('Mode', style:styleBuilder(14),),
      value: _selectedValue,  // 选中的值
      icon: Icon(Icons.arrow_drop_down),
      elevation: 16,
      style: TextStyle(color: Colors.blue),
      underline: Container(
        height: 2,
        color: Colors.blueAccent,
      ),
      onChanged: (String? newValue) {
        setState(() {
          _selectedValue = newValue;  // 当用户选择时更新状态
        });
      },
      items: _dropdownItems.map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),  // 将选项列表转换为 DropdownMenuItem 列表
    );
  }
}

TextStyle styleBuilder(double fontSize) {
  return TextStyle(
      fontSize: fontSize,
      color: Colors.white
  );
}

/// This is the Test Region to test the code generated by Chatgpt
class ChatTestRegion extends StatefulWidget {
  const ChatTestRegion({super.key});

  @override
  State<ChatTestRegion> createState() => _ChatTestRegionState();
}

class _ChatTestRegionState extends State<ChatTestRegion> {
  Offset _mousePosition = Offset(0, 0);  // 用于存储鼠标的局部位置
  bool _showBox = false;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Follow Mouse Box')),
        body: Stack(
          children: [
            // 使用 MouseRegion 监听鼠标位置
            MouseRegion(
              onEnter: (event) {
                setState(() {
                  _showBox = true;
                });
              },
              onExit: (event) {
                _showBox = false;
              },
              onHover: (event) {
                setState(() {
                  _mousePosition = event.localPosition;  // 获取鼠标相对于本地区域的坐标
                });
              },
              child: Center(
                child: Container(
                  width: 300,
                  height: 300,
                  color: Colors.blue.withOpacity(0.2),
                  child: Center(
                    child: Text(
                      'Hover here',
                      style: TextStyle(fontSize: 24),
                    ),
                  ),
                ),
              ),
            ),

            // Box 显示在鼠标位置
            if (_showBox)
              Positioned(
                left: _mousePosition.dx + 15,  // Box 位于鼠标的右下方
                top: _mousePosition.dy + 15,
                child: Container(
                  padding: EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: Colors.black.withOpacity(0.7),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Text(
                    'x: ${_mousePosition.dx.toStringAsFixed(1)}, y: ${_mousePosition.dy.toStringAsFixed(1)}',
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
}